import express from "express";
import HomeApproval from "./model.js";
import User from "../user/model.js";
import auth from "../token/auth.js";

const router = express.Router();

// 创建审批申请
router.post("/", auth, async (req, res) => {
  const { userId, newName, newImageUrl, newVideoUrl } = req.body;
  if (!userId || !newName || !newImageUrl || !newVideoUrl) {
    return res.status(400).json({ error: "缺少必要字段" });
  }
  try {
    const approval = new HomeApproval({
      userId,
      newName,
      newImageUrl,
      newVideoUrl,
      status: "待审批",
    });
    await approval.save();
    res.json({ message: "申请已提交", approval });
  } catch (err) {
    res.status(500).json({ error: "申请提交失败" });
  }
});

// 获取所有审批申请
router.get("/", auth, async (req, res) => {
  try {
    const approvals = await HomeApproval.find().populate(
      "userId",
      "name account"
    );
    res.json(approvals);
  } catch (err) {
    res.status(500).json({ error: "获取审批列表失败" });
  }
});

// 获取单个审批申请
router.get("/:id", auth, async (req, res) => {
  try {
    const approval = await HomeApproval.findById(req.params.id).populate(
      "userId",
      "name account"
    );
    if (!approval) {
      return res.status(404).json({ error: "审批申请不存在" });
    }
    res.json(approval);
  } catch (err) {
    res.status(500).json({ error: "获取审批申请失败" });
  }
});

// 获取指定用户的所有审批申请
router.get("/user/:userId", auth, async (req, res) => {
  const { userId } = req.params;
  try {
    const approvals = await HomeApproval.find({ userId }).populate(
      "userId",
      "name account"
    );
    res.json(approvals);
  } catch (err) {
    res.status(500).json({ error: "获取该用户审批申请失败" });
  }
});

// 更新审批申请（如审批状态、说明和视频链接）
router.put("/:id", auth, async (req, res) => {
  const { status, remark, operatorId, newName, newImageUrl, newVideoUrl } =
    req.body;
  if (!operatorId) {
    return res.status(400).json({ error: "缺少操作者id" });
  }

  let isAdmin = false;
  // 判断操作者身份
  const operator = await User.findById(operatorId);
  if (operator && ["社长", "管理员"].includes(operator.position)) {
    isAdmin = true;
  }

  // 如果要更改审批状态，必须是社长或管理员
  if (status) {
    if (!isAdmin) {
      return res
        .status(403)
        .json({ error: "只有社长或管理员可以更改审批状态" });
    }
    if (!["已通过", "待审批", "未通过"].includes(status)) {
      return res.status(400).json({ error: "审批状态不合法" });
    }
  }

  try {
    const updateData = {};
    if (status && isAdmin) updateData.status = status;
    if (remark) updateData.remark = remark;
    if (newName) updateData.newName = newName;
    if (newVideoUrl) updateData.newVideoUrl = newVideoUrl;
    if (newImageUrl) updateData.newImageUrl = newImageUrl;

    // 非社长/管理员更新时，强制状态为“待审批”
    if (!isAdmin) {
      updateData.status = "待审批";
    }

    const approval = await HomeApproval.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );
    if (!approval) {
      return res.status(404).json({ error: "审批申请不存在" });
    }
    res.json({ message: "更新成功", approval });
  } catch (err) {
    res.status(500).json({ error: "更新失败" });
  }
});

// 删除审批申请
router.delete("/:id", auth, async (req, res) => {
  const { operatorId } = req.body;
  if (!operatorId) {
    return res.status(400).json({ error: "缺少操作者id" });
  }
  // 查询操作者身份
  const operator = await User.findById(operatorId);
  if (!operator || !["社长", "管理员"].includes(operator.position)) {
    return res.status(403).json({ error: "只有社长或管理员可以删除审批" });
  }
  try {
    const approval = await HomeApproval.findByIdAndDelete(req.params.id);
    if (!approval) {
      return res.status(404).json({ error: "审批申请不存在" });
    }
    res.json({ message: "删除成功" });
  } catch (err) {
    res.status(500).json({ error: "删除失败" });
  }
});

export default router;
